<?php
/**
 * Created by PhpStorm.
 * User: cephei
 * Date: 12/2/15
 * Time: 5:28 PM
 */

namespace Plugins\Cron;

use Core\PluginContainer;

class Plugin_Cron
{
    private $db;
    private $step=60;

    public function __construct(){
        $this->db = PluginContainer::getInstance()->make('database');
        $this->step = $this->db->first("select value from plg_settings where attribute='timestep' and pluginname='cron'")->value;
    }

    public function addCronTask($name,$plugin, $method,$time=60,$args = [])
    {
        $this->db->insert('plg_cron_tasks',["name"=>$name,"plugin"=>$plugin,"method"=>$method,"args"=>json_encode($args),"time"=>$time]);
    }

    public function appendTask($name,$plugin, $method,$time=60,$args = []){
        $plugin = addslashes($plugin);
        if(empty($this->db->first("select * from plg_cron_tasks where name ='$name'")))
            $this->addCronTask($name,$plugin, $method,$time,$args);
        else{
            if($this->db->first("select * from plg_cron_tasks where name ='$name'")->time<=0)
                $this->db->update("plg_cron_tasks",["time"=>$time]," where name =$name");
        }
    }

    public function exec(){
        $taskList = $this->db->get('select * from plg_cron_tasks');
        foreach($taskList as $task) {
            $this->db->query("update plg_cron_tasks set time=(time-$this->step) where id=$task->id");
            if($task->time<=0) {
                $instance = new $task->plugin();
                if ($instance == null)
                    continue;
                $method = $task->method;
                $args = json_decode($task->args);
                call_user_func_array([$instance, $method], $args);
                $log = PluginContainer::getInstance()->make("log");
                if ($log != null)
                    $log->dailyLog("Task - $task->name has been executed");
            }
        }

    }

    public function changeStep($time){
        if(!empty($time)) {
            $this->step = $time;
            $this->db->update("plg_settings", ["timestep" => $time], " where pluginname='cron'");
        }
    }
}